<template>
	<view class="authorize">
		<!-- <button open-type="getUserInfo" lang="zh_CN" @getuserinfo="getUserInfo">授权登录</button> -->
		<view v-if="canIUse">
			<view class='header'>
				<image src="../../static/img/weixinBig.png"></image>
			</view>
			<view class='content'>
				<view>申请获取以下权限</view>
				<text class="text">获得你的公开信息(昵称，头像等)</text>
			</view>
			<button @getuserinfo="getUserInfo" class='bottom' open-type="getUserInfo" lang="zh_CN">授权登录</button>
		</view>
		<view v-else>请升级微信版本</view>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				canIUse: uni.canIUse('button.open-type.getUserInfo'), //判断小程序的API，回调，参数，组件等是否在当前版本可用。
				userInfo: {}
			}
		},
		methods: {
			...mapMutations(['setLoginState']),
			getUserInfo(e) { // 获取微信用户基础信息
				// console.log(e.detail.userInfo)
				let isConfirm = e.detail.userInfo //判断用户点击是否允许授权
				isConfirm ? uni.login({ //点击允许的回调
					provider: 'weixin',
					success: (loginRes) => {
						this.userInfo.code = loginRes.code
						this.userInfo.nickname = e.detail.userInfo.nickName // 微信用户名
						this.userInfo.image_url = e.detail.userInfo.avatarUrl // 微信用户头像
						this.getOpenId()
					}
				}) : uni.showModal({ //点击拒绝的回调
					title: '警告',
					content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
					showCancel: false,
					confirmText: '返回授权',
					success: function(res) {
						res.confirm ? console.log('用户点击了“返回授权”') : ''
					}
				})
			},
			getOpenId() { // 登录获取openId
				this.$request({
					url: this.$store.state.baseUrl + '/lwj/user_login',
					data: this.userInfo,
					success: res => {
						if (res.data.code === 1) {
							let loginState = {}
							loginState.uid = res.data.data.openid
							loginState.avatarUrl = this.userInfo.image_url
							loginState.hasLogin = true
							loginState.userName = this.userInfo.nickname
							this.setLoginState(loginState) // 设置全局登录状态与数据
							uni.navigateBack({
								delta: 1
							});
						}
					}
				})
			}

		}
	}
</script>

<style scoped>
	.authorize {
		width: 100%;
	}

	.authorize .header {
		width: 100%-80upx;
		height: 300upx;
		margin: 50upx 40upx 20upx 40upx;
		border-bottom: 1px solid #ccc;
		text-align: center;
	}

	.authorize .header image {
		height: 200upx;
		width: 200upx;
	}

	.authorize .content {
		width: 100%-80upx;
		margin: 0 40upx 100upx 40upx;
		border-radius: 20upx;
	}

	.authorize .content .text {
		display: block;
		color: #9d9d9d;
		margin-top: 40upx;
	}

	.authorize .bottom {
		width: 85%;
		border-radius: 80upx;
		margin: 70upx auto;
		font-size: 35upx;
		/* 微信logo的RGB色号 */
		background-color: rgb(69,174,74);
		color: #fff;
	}
</style>
